<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="站点" prop="siteId">
        <el-select v-model="queryParams.siteId" placeholder="请选择站点" clearable>
          <el-option
            v-for="site in siteList"
            :key="site.siteId"
            :label="site.siteName"
            :value="site.siteId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="任务状态" prop="taskStatus">
        <el-select v-model="queryParams.taskStatus" placeholder="请选择任务状态" clearable>
          <el-option label="待执行" value="0" />
          <el-option label="执行中" value="1" />
          <el-option label="已完成" value="2" />
          <el-option label="失败" value="3" />
          <el-option label="已停止" value="4" />
          <el-option label="已暂停" value="5" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['collect:task:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['collect:task:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="RefreshRight"
          @click="handleRefresh"
        >刷新</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="任务ID" align="center" prop="taskId" width="80" />
      <el-table-column label="任务名称" align="center" prop="taskName" :show-overflow-tooltip="true" />
      <el-table-column label="站点名称" align="center" prop="siteName" />
      <el-table-column label="采集类型" align="center" prop="collectType">
        <template #default="scope">
          <el-tag v-if="scope.row.collectType === 'list'" type="primary">列表</el-tag>
          <el-tag v-else-if="scope.row.collectType === 'detail'" type="success">详情</el-tag>
          <el-tag v-else>{{ scope.row.collectType }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="任务状态" align="center" prop="taskStatus">
        <template #default="scope">
          <el-tag v-if="scope.row.taskStatus === '0'" type="info">待执行</el-tag>
          <el-tag v-else-if="scope.row.taskStatus === '1'" type="primary">
            <el-icon class="is-loading"><Loading /></el-icon> 执行中
          </el-tag>
          <el-tag v-else-if="scope.row.taskStatus === '2'" type="success">已完成</el-tag>
          <el-tag v-else-if="scope.row.taskStatus === '3'" type="danger">失败</el-tag>
          <el-tag v-else-if="scope.row.taskStatus === '4'" type="warning">已停止</el-tag>
          <el-tag v-else-if="scope.row.taskStatus === '5'" type="warning">已暂停</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="进度" align="center" prop="progress" width="200">
        <template #default="scope">
          <el-progress
            :percentage="scope.row.progress || 0"
            :status="scope.row.taskStatus === '2' ? 'success' : (scope.row.taskStatus === '3' ? 'exception' : '')"
          >
            <span>{{ scope.row.currentPage || 0 }}/{{ scope.row.totalPages || 0 }}页</span>
          </el-progress>
        </template>
      </el-table-column>
      <el-table-column label="采集统计" align="center" width="150">
        <template #default="scope">
          <div>
            <el-tag type="success" size="small">成功: {{ scope.row.successCount || 0 }}</el-tag>
            <el-tag type="danger" size="small">失败: {{ scope.row.failureCount || 0 }}</el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.startTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="220">
        <template #default="scope">
          <el-button
            v-if="scope.row.taskStatus === '0'"
            size="small"
            type="primary"
            link
            icon="VideoPlay"
            @click="handleExecute(scope.row)"
            v-hasPermi="['collect:task:execute']"
          >执行</el-button>
          <el-button
            v-if="scope.row.taskStatus === '1'"
            size="small"
            type="primary"
            link
            icon="VideoPause"
            @click="handlePause(scope.row)"
            v-hasPermi="['collect:task:pause']"
          >暂停</el-button>
          <el-button
            v-if="scope.row.taskStatus === '5'"
            size="small"
            type="primary"
            link
            icon="VideoPlay"
            @click="handleResume(scope.row)"
            v-hasPermi="['collect:task:resume']"
          >恢复</el-button>
          <el-button
            v-if="scope.row.taskStatus === '1' || scope.row.taskStatus === '5'"
            size="small"
            type="primary"
            link
            icon="Close"
            @click="handleStop(scope.row)"
            v-hasPermi="['collect:task:stop']"
          >停止</el-button>
          <el-button
            size="small"
            type="primary"
            link
            icon="View"
            @click="handleView(scope.row)"
          >详情</el-button>
          <el-button
            v-if="scope.row.taskStatus !== '1'"
            size="small"
            type="primary"
            link
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['collect:task:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加任务对话框 -->
    <el-dialog title="新建采集任务" v-model="open" width="600px" append-to-body>
      <el-form ref="taskRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="采集站点" prop="siteId">
          <el-select v-model="form.siteId" placeholder="请选择采集站点" @change="handleSiteChange">
            <el-option
              v-for="site in siteList"
              :key="site.siteId"
              :label="site.siteName"
              :value="site.siteId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="采集方式" prop="collectType">
          <el-radio-group v-model="form.collectType">
            <el-radio label="list">列表采集</el-radio>
            <el-radio label="detail">详情采集</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="类型过滤" prop="typeFilter" v-if="form.collectType === 'list'">
          <el-input v-model="form.typeFilter" placeholder="可选，输入远程类型ID" />
        </el-form-item>
        <el-form-item label="小时数" prop="hours" v-if="form.collectType === 'list'">
          <el-input-number v-model="form.hours" :min="0" :max="720" placeholder="可选，采集最近N小时的数据" />
        </el-form-item>
        <el-form-item label="ID列表" prop="ids" v-if="form.collectType === 'detail'">
          <el-input v-model="form.ids" type="textarea" placeholder="请输入要采集的ID列表，逗号分隔" />
        </el-form-item>
        <el-form-item label="关键词" prop="keyword">
          <el-input v-model="form.keyword" placeholder="可选，按关键词过滤" />
        </el-form-item>
        <el-form-item label="任务类型" prop="taskType">
          <el-radio-group v-model="form.taskType">
            <el-radio label="0">手动任务</el-radio>
            <el-radio label="1">定时任务</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 任务详情对话框 -->
    <el-dialog title="任务详情" v-model="detailOpen" width="700px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="任务ID">{{ taskDetail.taskId }}</el-descriptions-item>
        <el-descriptions-item label="任务名称">{{ taskDetail.taskName }}</el-descriptions-item>
        <el-descriptions-item label="站点名称">{{ taskDetail.siteName }}</el-descriptions-item>
        <el-descriptions-item label="站点URL">{{ taskDetail.siteUrl }}</el-descriptions-item>
        <el-descriptions-item label="任务状态">
          <el-tag v-if="taskDetail.taskStatus === '0'" type="info">待执行</el-tag>
          <el-tag v-else-if="taskDetail.taskStatus === '1'" type="primary">执行中</el-tag>
          <el-tag v-else-if="taskDetail.taskStatus === '2'" type="success">已完成</el-tag>
          <el-tag v-else-if="taskDetail.taskStatus === '3'" type="danger">失败</el-tag>
          <el-tag v-else-if="taskDetail.taskStatus === '4'" type="warning">已停止</el-tag>
          <el-tag v-else-if="taskDetail.taskStatus === '5'" type="warning">已暂停</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="采集进度">
          <el-progress :percentage="taskDetail.progress || 0"></el-progress>
        </el-descriptions-item>
        <el-descriptions-item label="当前页/总页">
          {{ taskDetail.currentPage || 0 }} / {{ taskDetail.totalPages || 0 }}
        </el-descriptions-item>
        <el-descriptions-item label="已采集数量">{{ taskDetail.collectedCount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="成功数量">{{ taskDetail.successCount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="失败数量">{{ taskDetail.failureCount || 0 }}</el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ parseTime(taskDetail.startTime) }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ parseTime(taskDetail.endTime) }}</el-descriptions-item>
        <el-descriptions-item label="执行时长">{{ taskDetail.duration }} 秒</el-descriptions-item>
        <el-descriptions-item label="错误信息" :span="2">
          <span style="color: red">{{ taskDetail.errorMessage }}</span>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CollectTask">
import { listTask, getTask, delTask, addTask, executeTask, stopTask, pauseTask, resumeTask } from "@/api/collect/task";
import { listSite } from "@/api/collect/site";

const { proxy } = getCurrentInstance();

const taskList = ref([]);
const siteList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const detailOpen = ref(false);
const taskDetail = ref({});
const refreshTimer = ref(null);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    taskName: null,
    siteId: null,
    taskStatus: null
  },
  rules: {
    taskName: [
      { required: true, message: "任务名称不能为空", trigger: "blur" }
    ],
    siteId: [
      { required: true, message: "采集站点不能为空", trigger: "change" }
    ],
    collectType: [
      { required: true, message: "采集方式不能为空", trigger: "change" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询采集任务列表 */
function getList() {
  loading.value = true;
  listTask(queryParams.value).then(response => {
    taskList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 查询站点列表 */
function getSiteList() {
  listSite({ pageSize: 100 }).then(response => {
    siteList.value = response.rows;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    taskId: null,
    taskName: null,
    siteId: null,
    siteName: null,
    siteUrl: null,
    siteFlag: null,
    collectType: "list",
    taskType: "0",
    typeFilter: null,
    hours: null,
    ids: null,
    keyword: null
  };
  proxy.resetForm("taskRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 刷新按钮操作 */
function handleRefresh() {
  getList();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.taskId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加采集任务";
}

/** 站点选择变化 */
function handleSiteChange(siteId) {
  const site = siteList.value.find(s => s.siteId === siteId);
  if (site) {
    form.value.siteName = site.siteName;
    form.value.siteUrl = site.siteUrl;
    form.value.siteFlag = site.siteFlag;
  }
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["taskRef"].validate(valid => {
    if (valid) {
      addTask(form.value).then(response => {
        proxy.$modal.msgSuccess("新增成功");
        open.value = false;
        getList();
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const taskIds = row.taskId || ids.value;
  proxy.$modal.confirm('是否确认删除采集任务编号为"' + taskIds + '"的数据项？').then(function() {
    return delTask(taskIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 执行任务 */
function handleExecute(row) {
  executeTask(row.taskId).then(response => {
    proxy.$modal.msgSuccess("任务开始执行");
    getList();
  });
}

/** 暂停任务 */
function handlePause(row) {
  pauseTask(row.taskId).then(response => {
    proxy.$modal.msgSuccess("任务已暂停");
    getList();
  });
}

/** 恢复任务 */
function handleResume(row) {
  resumeTask(row.taskId).then(response => {
    proxy.$modal.msgSuccess("任务已恢复");
    getList();
  });
}

/** 停止任务 */
function handleStop(row) {
  proxy.$modal.confirm('确认要停止该任务吗？').then(function() {
    return stopTask(row.taskId);
  }).then(() => {
    proxy.$modal.msgSuccess("任务已停止");
    getList();
  }).catch(() => {});
}

/** 查看详情 */
function handleView(row) {
  getTask(row.taskId).then(response => {
    taskDetail.value = response.data;
    detailOpen.value = true;
  });
}

/** 启动自动刷新 */
function startAutoRefresh() {
  refreshTimer.value = setInterval(() => {
    // 只有当有执行中的任务时才刷新
    const hasRunningTask = taskList.value.some(task =>
      task.taskStatus === '1' || task.taskStatus === '5'
    );
    if (hasRunningTask) {
      getList();
    }
  }, 3000); // 3秒刷新一次
}

/** 停止自动刷新 */
function stopAutoRefresh() {
  if (refreshTimer.value) {
    clearInterval(refreshTimer.value);
    refreshTimer.value = null;
  }
}

// 初始化
getList();
getSiteList();
startAutoRefresh();

// 组件卸载时清理定时器
onUnmounted(() => {
  stopAutoRefresh();
});
</script>
